const crypto = require('crypto')
const superagent = require('superagent')

let get_jd_promotion_link = function(item_link, after_get_jd_promotion_link){
    let method = 'jingdong.service.promotion.getcode'
    let access_token = "9204574c-f17c-4d66-b9a6-29b2902d1336"
    let app_key = '13D5651EE8DDD042E38294261D6D58BA'
    let app_secret = '5433ce0d44ad49e1b43a9ee5b4734cf5'
    let v = '2.0'
    let timestamp = new Date().toLocaleString()
    let obj = {
        method: method,
        access_token: access_token,
        app_key: app_key,
        v: v,
        timestamp: timestamp
    }
    let keys = Object.keys(obj).sort()
    let values = ''
    for(let i = 0; i < keys.length; i++){
        values = values + keys[i] + obj[keys[i]]
    }
    let new_values = app_secret + values + app_secret
    let hash = crypto.createHash('MD5')
    hash.update(new_values)
    let origin_sign = hash.digest('hex')
    let sign = origin_sign.toUpperCase()
    // console.log(sign)

    let promotionType = 7
    let materialId = item_link
    let unionId = 1000040154
    let channel = 'PC'
    let webId = '1136405193'
    let param = {
        promotionType: promotionType,
        materialId: materialId,
        unionId: unionId,
        channel: channel,
        webId: webId
    }

    let url = 'https://api.jd.com/routerjson?360buy_param_json=' + JSON.stringify(param) + '&access_token=' + access_token + '&app_key=' + app_key + '&method=' + method + '&timestamp=' + timestamp + '&v=' + v + '&sign=' + sign
    superagent.get(url)
    .end(function(err, res){
        if(JSON.parse(res.text).jingdong_service_promotion_getcode_responce.code != 0){
            after_get_jd_promotion_link('')
        }else{
            let promotion_link = JSON.parse(JSON.parse(res.text).jingdong_service_promotion_getcode_responce.queryjs_result).url
            after_get_jd_promotion_link(promotion_link)
        }
    })
}
exports.get_jd_promotion_link = get_jd_promotion_link

get_jd_promotion_link('https://item.jd.com/4483022.html', function(link){
    console.log(link.length)
})


/*
{
"access_token": "9204574c-f17c-4d66-b9a6-29b2902d1336",
"code": 0,
"expires_in": 31535999,
"refresh_token": "c8343bc4-abfe-490b-8799-265d48f8d4e2",
"time": "1515494047511",
"token_type": "bearer",
"uid": "7857591699",
"user_nick": "duoshoumama"
}

access_token: 9204574c-f17c-4d66-b9a6-29b2902d1336
app_key: 13D5651EE8DDD042E38294261D6D58BA
app_secret: 5433ce0d44ad49e1b43a9ee5b4734cf5
promotionType: 7
materialId: https://item.jd.com/4483022.html
unionId: 1000040154
channel: PC
webId: 1136405193
adttype:6
*/